home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / ast.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  13KB  |  316 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5.     ast
  6.     ~~~
  7.  
  8.     The `ast` module helps Python applications to process trees of the Python
  9.     abstract syntax grammar.  The abstract syntax itself might change with
  10.     each Python release; this module helps to find out programmatically what
  11.     the current grammar looks like and allows modifications of it.
  12.  
  13.     An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
  14.     a flag to the `compile()` builtin function or by using the `parse()`
  15.     function from this module.  The result will be a tree of objects whose
  16.     classes all inherit from `ast.AST`.
  17.  
  18.     A modified abstract syntax tree can be compiled into a Python code object
  19.     using the built-in `compile()` function.
  20.  
  21.     Additionally various helper functions are provided that make working with
  22.     the trees simpler.  The main intention of the helper functions and this
  23.     module in general is to provide an easy to use interface for libraries
  24.     that work tightly with the python syntax (template engines for example).
  25.  
  26.  
  27.     :copyright: Copyright 2008 by Armin Ronacher.
  28.     :license: Python License.
  29. '''
  30. from _ast import *
  31. from _ast import __version__
  32.  
  33. def parse(expr, filename = '<unknown>', mode = 'exec'):
  34.     '''
  35.     Parse an expression into an AST node.
  36.     Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST).
  37.     '''
  38.     return compile(expr, filename, mode, PyCF_ONLY_AST)
  39.  
  40.  
  41. def literal_eval(node_or_string):
  42.     '''
  43.     Safely evaluate an expression node or a string containing a Python
  44.     expression.  The string or node provided may only consist of the following
  45.     Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
  46.     and None.
  47.     '''
  48.     _safe_names = {
  49.         'None': None,
  50.         'True': True,
  51.         'False': False }
  52.     if isinstance(node_or_string, basestring):
  53.         node_or_string = parse(node_or_string, mode = 'eval')
  54.     
  55.     if isinstance(node_or_string, Expression):
  56.         node_or_string = node_or_string.body
  57.     
  58.     
  59.     def _convert(node):
  60.         if isinstance(node, Str):
  61.             return node.s
  62.         if isinstance(node, Num):
  63.             return node.n
  64.         if isinstance(node, Tuple):
  65.             return tuple(map(_convert, node.elts))
  66.         if isinstance(node, List):
  67.             return list(map(_convert, node.elts))
  68.         if isinstance(node, Dict):
  69.             return (dict,)((lambda .0: for k, v in .0:
  70. (_convert(k), _convert(v)))(zip(node.keys, node.values)))
  71.         raise ValueError('malformed string')
  72.  
  73.     return _convert(node_or_string)
  74.  
  75.  
  76. def dump(node, annotate_fields = True, include_attributes = False):
  77.     '''
  78.     Return a formatted dump of the tree in *node*.  This is mainly useful for
  79.     debugging purposes.  The returned string will show the names and the values
  80.     for fields.  This makes the code impossible to evaluate, so if evaluation is
  81.     wanted *annotate_fields* must be set to False.  Attributes such as line
  82.     numbers and column offsets are not dumped by default.  If this is wanted,
  83.     *include_attributes* can be set to True.
  84.     '''
  85.     
  86.     def _format(node):
  87.         if isinstance(node, AST):
  88.             fields = [ (a, _format(b)) for a, b in iter_fields(node) ]
  89.             rv = [] % ('%s(%s', node.__class__.__name__(', '.join if annotate_fields else (lambda .0: for a, b in .0:
  90. b)(fields)))
  91.             return rv + ')'
  92.         if isinstance(node, list):
  93.             return '[%s]' % (', '.join,)((lambda .0: for x in .0:
  94. _format(x))(node))
  95.         return repr(node)
  96.  
  97.     if not isinstance(node, AST):
  98.         raise TypeError('expected AST, got %r' % node.__class__.__name__)
  99.     isinstance(node, AST)
  100.     return _format(node)
  101.  
  102.  
  103. def copy_location(new_node, old_node):
  104.     '''
  105.     Copy source location (`lineno` and `col_offset` attributes) from
  106.     *old_node* to *new_node* if possible, and return *new_node*.
  107.     '''
  108.     for attr in ('lineno', 'col_offset'):
  109.         if attr in old_node._attributes and attr in new_node._attributes and hasattr(old_node, attr):
  110.             setattr(new_node, attr, getattr(old_node, attr))
  111.             continue
  112.     
  113.     return new_node
  114.  
  115.  
  116. def fix_missing_locations(node):
  117.     '''
  118.     When you compile a node tree with compile(), the compiler expects lineno and
  119.     col_offset attributes for every node that supports them.  This is rather
  120.     tedious to fill in for generated nodes, so this helper adds these attributes
  121.     recursively where not already set, by setting them to the values of the
  122.     parent node.  It works recursively starting at *node*.
  123.     '''
  124.     
  125.     def _fix(node, lineno, col_offset):
  126.         if 'lineno' in node._attributes:
  127.             if not hasattr(node, 'lineno'):
  128.                 node.lineno = lineno
  129.             else:
  130.                 lineno = node.lineno
  131.         
  132.         if 'col_offset' in node._attributes:
  133.             if not hasattr(node, 'col_offset'):
  134.                 node.col_offset = col_offset
  135.             else:
  136.                 col_offset = node.col_offset
  137.         
  138.         for child in iter_child_nodes(node):
  139.             _fix(child, lineno, col_offset)
  140.         
  141.  
  142.     _fix(node, 1, 0)
  143.     return node
  144.  
  145.  
  146. def increment_lineno(node, n = 1):
  147.     '''
  148.     Increment the line number of each node in the tree starting at *node* by *n*.
  149.     This is useful to "move code" to a different location in a file.
  150.     '''
  151.     if 'lineno' in node._attributes:
  152.         node.lineno = getattr(node, 'lineno', 0) + n
  153.     
  154.     for child in walk(node):
  155.         if 'lineno' in child._attributes:
  156.             child.lineno = getattr(child, 'lineno', 0) + n
  157.             continue
  158.     
  159.     return node
  160.  
  161.  
  162. def iter_fields(node):
  163.     '''
  164.     Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
  165.     that is present on *node*.
  166.     '''
  167.     for field in node._fields:
  168.         
  169.         try:
  170.             yield (field, getattr(node, field))
  171.         continue
  172.         except AttributeError:
  173.             continue
  174.         
  175.  
  176.     
  177.  
  178.  
  179. def iter_child_nodes(node):
  180.     '''
  181.     Yield all direct child nodes of *node*, that is, all fields that are nodes
  182.     and all items of fields that are lists of nodes.
  183.     '''
  184.     for name, field in iter_fields(node):
  185.         if isinstance(field, AST):
  186.             yield field
  187.             continue
  188.         if isinstance(field, list):
  189.             for item in field:
  190.                 if isinstance(item, AST):
  191.                     yield item
  192.                     continue
  193.             
  194.     
  195.  
  196.  
  197. def get_docstring(node, clean = True):
  198.     '''
  199.     Return the docstring for the given node or None if no docstring can
  200.     be found.  If the node provided does not have docstrings a TypeError
  201.     will be raised.
  202.     '''
  203.     if not isinstance(node, (FunctionDef, ClassDef, Module)):
  204.         raise TypeError("%r can't have docstrings" % node.__class__.__name__)
  205.     isinstance(node, (FunctionDef, ClassDef, Module))
  206.     if node.body and isinstance(node.body[0], Expr) and isinstance(node.body[0].value, Str):
  207.         if clean:
  208.             import inspect as inspect
  209.             return inspect.cleandoc(node.body[0].value.s)
  210.         return node.body[0].value.s
  211.  
  212.  
  213. def walk(node):
  214.     """
  215.     Recursively yield all child nodes of *node*, in no specified order.  This is
  216.     useful if you only want to modify nodes in place and don't care about the
  217.     context.
  218.     """
  219.     deque = deque
  220.     import collections
  221.     todo = deque([
  222.         node])
  223.     while todo:
  224.         node = todo.popleft()
  225.         todo.extend(iter_child_nodes(node))
  226.         yield node
  227.  
  228.  
  229. class NodeVisitor(object):
  230.     """
  231.     A node visitor base class that walks the abstract syntax tree and calls a
  232.     visitor function for every node found.  This function may return a value
  233.     which is forwarded by the `visit` method.
  234.  
  235.     This class is meant to be subclassed, with the subclass adding visitor
  236.     methods.
  237.  
  238.     Per default the visitor functions for the nodes are ``'visit_'`` +
  239.     class name of the node.  So a `TryFinally` node visit function would
  240.     be `visit_TryFinally`.  This behavior can be changed by overriding
  241.     the `visit` method.  If no visitor function exists for a node
  242.     (return value `None`) the `generic_visit` visitor is used instead.
  243.  
  244.     Don't use the `NodeVisitor` if you want to apply changes to nodes during
  245.     traversing.  For this a special visitor exists (`NodeTransformer`) that
  246.     allows modifications.
  247.     """
  248.     
  249.     def visit(self, node):
  250.         '''Visit a node.'''
  251.         method = 'visit_' + node.__class__.__name__
  252.         visitor = getattr(self, method, self.generic_visit)
  253.         return visitor(node)
  254.  
  255.     
  256.     def generic_visit(self, node):
  257.         '''Called if no explicit visitor function exists for a node.'''
  258.         for field, value in iter_fields(node):
  259.             if isinstance(value, list):
  260.                 for item in value:
  261.                     if isinstance(item, AST):
  262.                         self.visit(item)
  263.                         continue
  264.                 
  265.             if isinstance(value, AST):
  266.                 self.visit(value)
  267.                 continue
  268.         
  269.  
  270.  
  271.  
  272. class NodeTransformer(NodeVisitor):
  273.     """
  274.     A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
  275.     allows modification of nodes.
  276.  
  277.     The `NodeTransformer` will walk the AST and use the return value of the
  278.     visitor methods to replace or remove the old node.  If the return value of
  279.     the visitor method is ``None``, the node will be removed from its location,
  280.     otherwise it is replaced with the return value.  The return value may be the
  281.     original node in which case no replacement takes place.
  282.  
  283.     Here is an example transformer that rewrites all occurrences of name lookups
  284.     (``foo``) to ``data['foo']``::
  285.  
  286.        class RewriteName(NodeTransformer):
  287.  
  288.            def visit_Name(self, node):
  289.                return copy_location(Subscript(
  290.                    value=Name(id='data', ctx=Load()),
  291.                    slice=Index(value=Str(s=node.id)),
  292.                    ctx=node.ctx
  293.                ), node)
  294.  
  295.     Keep in mind that if the node you're operating on has child nodes you must
  296.     either transform the child nodes yourself or call the :meth:`generic_visit`
  297.     method for the node first.
  298.  
  299.     For nodes that were part of a collection of statements (that applies to all
  300.     statement nodes), the visitor may also return a list of nodes rather than
  301.     just a single node.
  302.  
  303.     Usually you use the transformer like this::
  304.  
  305.        node = YourTransformer().visit(node)
  306.     """
  307.     
  308.     def generic_visit(self, node):
  309.         for field, old_value in iter_fields(node):
  310.             old_value = getattr(node, field, None)
  311.             None if isinstance(old_value, list) else new_node is None
  312.         
  313.         return node
  314.  
  315.  
  316.